package io.xiaojl.xj2ee.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

import io.xiaojl.xj2ee.kit.PageKit;
import io.xiaojl.xj2ee.kit.Query;
import io.xiaojl.xj2ee.kit.R;
import io.xiaojl.xj2ee.service.GeneratorService;

/**
 * 
 * <p>Title: GeneratorController</p>  
 *
 * <p>Description: 代码生成器控制层</p>  
 *
 * @author jilong.xiao  
 * @date 2018年5月25日
 */
@Controller
@RequestMapping("/generator")
public class GeneratorController {
	@Autowired
	private GeneratorService generatorService;
	
	/**
	 * 列表
	 */
	@ResponseBody
	@RequestMapping("/list")
	public R list(@RequestParam Map<String, Object> params){
		//查询列表数据
		Query query = new Query(params);
		List<Map<String, Object>> list = generatorService.queryList(query);
		int total = generatorService.queryTotal(query);
		
		PageKit pageUtil = new PageKit(list, total, query.getLimit(), query.getPage());
		
		return R.ok().put("page", pageUtil);
	}
	
	/**
	 * 生成代码
	 */
	@RequestMapping("/code")
	public void code(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String[] tableNames = new String[]{};
		String tables = request.getParameter("tables");
		tableNames = JSON.parseArray(tables).toArray(tableNames);
		
		byte[] data = generatorService.generatorCode(tableNames);
		
		response.reset();  
        response.setHeader("Content-Disposition", "attachment; filename=\"xjee_gen_code.zip\"");  
        response.addHeader("Content-Length", "" + data.length);  
        response.setContentType("application/octet-stream; charset=UTF-8");  
  
        IOUtils.write(data, response.getOutputStream());  
	}
}
